package com.huike.aspect;

import com.huike.crmlog.pojos.CrmLog;
import com.huike.log.Log;
import com.huike.mapper.CrmLogMapper;
import com.huike.mapper.UserMapper;
import com.huike.utils.IpAddressUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.servlet.mvc.condition.RequestConditionHolder;

import javax.servlet.http.HttpServletRequest;
import java.lang.annotation.Annotation;
import java.time.LocalDateTime;

@Aspect
@Component
public class LogAspect {
    @Autowired
    private CrmLogMapper crmLogMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private IpAddressUtils ipAddressUtils;
    //切入点
    @Pointcut("@annotation(com.huike.log.Log)")
    public void pointCut(){}
    //通知
    @AfterReturning(pointcut = "pointCut()",returning = "jsonReturn")
    public void doAfter(JoinPoint joinPoint,Object jsonReturn){
        CrmLog crmLog=new CrmLog();
        MethodSignature methodSignature = (MethodSignature)joinPoint.getSignature();
        Log annotation = methodSignature.getMethod().getAnnotation(Log.class);
        crmLog.setCreateTime(LocalDateTime.now());
        Integer userId=1;
        crmLog.setUserId(userId);
        String username = userMapper.selectById(userId).getName();
        crmLog.setUserName(username);
        //获取请求的ip地址
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String ipAddress = ipAddressUtils.getIpAddress(request);
        crmLog.setUserIp(ipAddress);
        //获取请求的url
        String requestURI = request.getRequestURI();
        crmLog.setRequestUrl(requestURI);
        //获取请求的模块名称
        String title = annotation.title();
        crmLog.setModuleName(title);
        //获取请求的方式
        String requestName = request.getMethod();
        crmLog.setRequestName(requestName);
        //写入数据库
        crmLogMapper.insert(crmLog);

    }
}
